/**
 * 监测站点管理系统 Controller
 * 
 * 包含三个核心控制器：
 * 1. StationTypeController - 测站数据要素管理控制器
 * 2. StationInfoController - 测站编码管理控制器  
 * 3. MonitoringDataController - 监测数据管理控制器
 * 
 * @author: [开发者名称]
 * @date: [创建日期]
 */

import { Controller, Get, Post, Put, Del, Body, Query, Param, Inject } from '@midwayjs/decorator';
import { ApiOperation, ApiResponse, ApiTags, ApiParam } from '@midwayjs/swagger';
import {
    StationTypeService,
    StationInfoService,
    MonitoringDataService
} from '../service/stationManage.service';
import {
    CreateStationTypeDTO,
    UpdateStationTypeDTO,
    QueryStationTypeDTO,
    StationTypeResponseDTO,
    CreateStationInfoDTO,
    UpdateStationInfoDTO,
    QueryStationInfoDTO,
    StationInfoResponseDTO,
    CreateMonitoringDataDTO,
    UpdateMonitoringDataDTO,
    QueryMonitoringDataDTO,
    MonitoringDataResponseDTO,
    BatchImportStationInfoDTO,
    BatchImportMonitoringDataDTO,
    BatchDeleteDTO,
    PageResultDTO,
    CommonResponseDTO,
    DataStatisticsDTO,
    BatchImportStationTypeDTO,
} from '../dto/stationManage.dto';

/**
 * 测站数据要素管理控制器
 */
@ApiTags('测站数据要素管理')
@Controller('/stationApi/station-type')
export class StationTypeController {
    @Inject()
    stationTypeService: StationTypeService;

    /**
     * 创建测站数据要素
     */
    @ApiOperation({ summary: '创建测站数据要素' })
    @ApiResponse({ status: 200, description: '创建成功', type: CommonResponseDTO })
    @Post('/')
    async create(@Body() createDto: CreateStationTypeDTO): Promise<CommonResponseDTO<StationTypeResponseDTO>> {
        try {
            const result = await this.stationTypeService.create(createDto);
            return {
                code: 200,
                message: '创建成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '创建失败',
                timestamp: Date.now()
            };
        }
    }

    /**
   * 批量导入测站数据要素
   */
    @ApiOperation({ summary: '批量导入测站数据要素' })
    @ApiResponse({ status: 200, description: '导入成功', type: CommonResponseDTO })
    @Post('/batch-import')
    async batchImport(@Body() batchImportDto: BatchImportStationTypeDTO): Promise<CommonResponseDTO<StationTypeResponseDTO[]>> {
        try {
            const result = await this.stationTypeService.batchImport(batchImportDto.stationTypeList);
            return {
                code: 200,
                message: `成功导入 ${result.length} 条记录`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '批量导入失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据ID查询测站数据要素
     */
    @ApiOperation({ summary: '根据ID查询测站数据要素' })
    @ApiParam({ name: 'id', description: '测站数据要素ID' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/:id')
    async findById(@Param('id') id: string): Promise<CommonResponseDTO<StationTypeResponseDTO | null>> {
        try {
            const result = await this.stationTypeService.findById(id);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 分页查询测站数据要素
     */
    @ApiOperation({ summary: '分页查询测站数据要素' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/')
    async findPage(@Query() queryDto: QueryStationTypeDTO): Promise<CommonResponseDTO<PageResultDTO<StationTypeResponseDTO>>> {
        try {
            const result = await this.stationTypeService.findPage(queryDto);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 查询所有测站数据要素
     */
    @ApiOperation({ summary: '查询所有测站数据要素' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/all')
    async findAll(): Promise<CommonResponseDTO<StationTypeResponseDTO[]>> {
        try {
            const result = await this.stationTypeService.findAll();
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 更新测站数据要素
     */
    @ApiOperation({ summary: '更新测站数据要素' })
    @ApiParam({ name: 'id', description: '测站数据要素ID' })
    @ApiResponse({ status: 200, description: '更新成功', type: CommonResponseDTO })
    @Put('/:id')
    async update(
        @Param('id') id: string,
        @Body() updateDto: UpdateStationTypeDTO
    ): Promise<CommonResponseDTO<StationTypeResponseDTO>> {
        try {
            const result = await this.stationTypeService.update(id, updateDto);
            return {
                code: 200,
                message: '更新成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '更新失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 删除测站数据要素
     */
    @ApiOperation({ summary: '删除测站数据要素' })
    @ApiParam({ name: 'id', description: '测站数据要素ID' })
    @ApiResponse({ status: 200, description: '删除成功', type: CommonResponseDTO })
    @Del('/:id')
    async delete(@Param('id') id: string): Promise<CommonResponseDTO<boolean>> {
        try {
            const result = await this.stationTypeService.delete(id);
            return {
                code: 200,
                message: result ? '删除成功' : '删除失败，记录不存在',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '删除失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 批量删除测站数据要素
     */
    @ApiOperation({ summary: '批量删除测站数据要素' })
    @ApiResponse({ status: 200, description: '删除成功', type: CommonResponseDTO })
    @Del('/batch')
    async batchDelete(@Body() batchDeleteDto: BatchDeleteDTO): Promise<CommonResponseDTO<number>> {
        try {
            const result = await this.stationTypeService.batchDelete(batchDeleteDto.ids);
            return {
                code: 200,
                message: `成功删除 ${result} 条记录`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '批量删除失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 检查编码是否存在
     */
    @ApiOperation({ summary: '检查测站数据要素编码是否存在' })
    @ApiResponse({ status: 200, description: '检查完成', type: CommonResponseDTO })
    @Get('/check-code/:code')
    async checkCodeExists(
        @Param('code') stationTypeCode: string,
        @Query('excludeId') excludeId?: string
    ): Promise<CommonResponseDTO<boolean>> {
        try {
            const exists = await this.stationTypeService.checkCodeExists(stationTypeCode, excludeId);
            return {
                code: 200,
                message: '检查完成',
                data: exists,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '检查失败',
                timestamp: Date.now()
            };
        }
    }
}

/**
 * 测站信息管理控制器
 */
@ApiTags('测站信息管理')
@Controller('/stationApi/station-info')
export class StationInfoController {
    @Inject()
    stationInfoService: StationInfoService;

    /**
     * 创建测站信息
     */
    @ApiOperation({ summary: '创建测站信息' })
    @ApiResponse({ status: 200, description: '创建成功', type: CommonResponseDTO })
    @Post('/')
    async create(@Body() createDto: CreateStationInfoDTO): Promise<CommonResponseDTO<StationInfoResponseDTO>> {
        try {
            const result = await this.stationInfoService.create(createDto);
            return {
                code: 200,
                message: '创建成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '创建失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据ID查询测站信息
     */
    @ApiOperation({ summary: '根据ID查询测站信息' })
    @ApiParam({ name: 'id', description: '测站信息ID' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/:id')
    async findById(@Param('id') id: string): Promise<CommonResponseDTO<StationInfoResponseDTO | null>> {
        try {
            const result = await this.stationInfoService.findById(id);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据测站编码查询
     */
    @ApiOperation({ summary: '根据测站编码查询' })
    @ApiParam({ name: 'stcd', description: '测站编码' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/by-stcd/:stcd')
    async findByStcd(@Param('stcd') stcd: string): Promise<CommonResponseDTO<StationInfoResponseDTO | null>> {
        try {
            const result = await this.stationInfoService.findByStcd(stcd);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 分页查询测站信息
     */
    @ApiOperation({ summary: '分页查询测站信息' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/')
    async findPage(@Query() queryDto: QueryStationInfoDTO): Promise<CommonResponseDTO<PageResultDTO<StationInfoResponseDTO>>> {
        try {
            const result = await this.stationInfoService.findPage(queryDto);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 查询所有测站信息
     */
    @ApiOperation({ summary: '查询所有测站信息' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/all')
    async findAll(): Promise<CommonResponseDTO<StationInfoResponseDTO[]>> {
        try {
            const result = await this.stationInfoService.findAll();
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据地理位置范围查询测站
     */
    @ApiOperation({ summary: '根据地理位置范围查询测站' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/by-location')
    async findByLocation(
        @Query('minLon') minLon: number,
        @Query('maxLon') maxLon: number,
        @Query('minLat') minLat: number,
        @Query('maxLat') maxLat: number
    ): Promise<CommonResponseDTO<StationInfoResponseDTO[]>> {
        try {
            const result = await this.stationInfoService.findByLocation(minLon, maxLon, minLat, maxLat);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 更新测站信息
     */
    @ApiOperation({ summary: '更新测站信息' })
    @ApiParam({ name: 'id', description: '测站信息ID' })
    @ApiResponse({ status: 200, description: '更新成功', type: CommonResponseDTO })
    @Put('/:id')
    async update(
        @Param('id') id: string,
        @Body() updateDto: UpdateStationInfoDTO
    ): Promise<CommonResponseDTO<StationInfoResponseDTO>> {
        try {
            const result = await this.stationInfoService.update(id, updateDto);
            return {
                code: 200,
                message: '更新成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '更新失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 删除测站信息
     */
    @ApiOperation({ summary: '删除测站信息' })
    @ApiParam({ name: 'id', description: '测站信息ID' })
    @ApiResponse({ status: 200, description: '删除成功', type: CommonResponseDTO })
    @Del('/:id')
    async delete(@Param('id') id: string): Promise<CommonResponseDTO<boolean>> {
        try {
            const result = await this.stationInfoService.delete(id);
            return {
                code: 200,
                message: result ? '删除成功' : '删除失败，记录不存在',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '删除失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 批量删除测站信息
     */
    @ApiOperation({ summary: '批量删除测站信息' })
    @ApiResponse({ status: 200, description: '删除成功', type: CommonResponseDTO })
    @Del('/batch')
    async batchDelete(@Body() batchDeleteDto: BatchDeleteDTO): Promise<CommonResponseDTO<number>> {
        try {
            const result = await this.stationInfoService.batchDelete(batchDeleteDto.ids);
            return {
                code: 200,
                message: `成功删除 ${result} 条记录`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '批量删除失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 批量导入测站信息
     */
    @ApiOperation({ summary: '批量导入测站信息' })
    @ApiResponse({ status: 200, description: '导入成功', type: CommonResponseDTO })
    @Post('/batch-import')
    async batchImport(@Body() batchImportDto: BatchImportStationInfoDTO): Promise<CommonResponseDTO<StationInfoResponseDTO[]>> {
        try {
            const result = await this.stationInfoService.batchImport(batchImportDto.stationInfoList);
            return {
                code: 200,
                message: `成功导入 ${result.length} 条记录`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '批量导入失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 检查测站编码是否存在
     */
    @ApiOperation({ summary: '检查测站编码是否存在' })
    @ApiResponse({ status: 200, description: '检查完成', type: CommonResponseDTO })
    @Get('/check-stcd/:stcd')
    async checkStcdExists(
        @Param('stcd') stcd: string,
        @Query('excludeId') excludeId?: string
    ): Promise<CommonResponseDTO<boolean>> {
        try {
            const exists = await this.stationInfoService.checkStcdExists(stcd, excludeId);
            return {
                code: 200,
                message: '检查完成',
                data: exists,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '检查失败',
                timestamp: Date.now()
            };
        }
    }
}


/**
 * 监测数据管理 Controller - 完整版
 * 支持 dataTypes 多选功能
 */

/**
 * 监测数据管理控制器 - 支持测站类型字段和 dataTypes 多选
 */
@ApiTags('监测数据管理')
@Controller('/stationApi/monitoring-data')
export class MonitoringDataController {
    @Inject()
    monitoringDataService: MonitoringDataService;

    /**
     * 创建监测数据
     */
    @ApiOperation({ summary: '创建监测数据' })
    @ApiResponse({ status: 200, description: '创建成功', type: CommonResponseDTO })
    @Post('/')
    async create(@Body() createDto: CreateMonitoringDataDTO): Promise<CommonResponseDTO<MonitoringDataResponseDTO>> {
        try {
            const result = await this.monitoringDataService.create(createDto);
            return {
                code: 200,
                message: '创建成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '创建失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据ID查询监测数据
     */
    @ApiOperation({ summary: '根据ID查询监测数据' })
    @ApiParam({ name: 'id', description: '监测数据ID' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/:id')
    async findById(@Param('id') id: string): Promise<CommonResponseDTO<MonitoringDataResponseDTO | null>> {
        try {
            const result = await this.monitoringDataService.findById(id);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

   /**
 * 处理 dataTypes 参数的工具函数
 */
private parseDataTypes(dataTypes: string[] | string | undefined): string[] | undefined {
    if (!dataTypes) return undefined;
    
    // 如果已经是数组，直接返回过滤后的结果
    if (Array.isArray(dataTypes)) {
        return dataTypes.filter(item => item && typeof item === 'string' && item.trim().length > 0);
    }
    
    // 如果是字符串，进行解析
    if (typeof dataTypes === 'string') {
        try {
            // 尝试 JSON 解析
            const parsed = JSON.parse(dataTypes);
            if (Array.isArray(parsed)) {
                return parsed.filter(item => item && typeof item === 'string' && item.trim().length > 0);
            }
        } catch {
            // JSON 解析失败，按逗号分割
            return dataTypes.split(',')
                .map(item => item.trim())
                .filter(item => item.length > 0);
        }
    }
    
    return undefined;
}

/**
 * 分页查询监测数据 - 支持 dataTypes 多选
 */
@ApiOperation({ summary: '分页查询监测数据，支持单选dataType和多选dataTypes' })
@ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
@Get('/')
async findPage(@Query() queryDto: QueryMonitoringDataDTO): Promise<CommonResponseDTO<PageResultDTO<MonitoringDataResponseDTO>>> {
    try {
        // 处理前端传来的 dataTypes 参数
        queryDto.dataTypes = this.parseDataTypes(queryDto.dataTypes);

        const result = await this.monitoringDataService.findPage(queryDto);
        return {
            code: 200,
            message: '查询成功',
            data: result,
            timestamp: Date.now()
        };
    } catch (error) {
        return {
            code: 500,
            message: error.message || '查询失败',
            timestamp: Date.now()
        };
    }
}

/**
 * 根据多个数据类型查询监测数据
 */
@ApiOperation({ summary: '根据多个数据类型查询监测数据' })
@ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
@Get('/by-data-types')
async findByDataTypes(
    @Query('dataTypes') dataTypesParam: string,
    @Query('stationCode') stationCode?: string,
    @Query('stationTypeCode') stationTypeCode?: string,
    @Query('limit') limit?: number
): Promise<CommonResponseDTO<MonitoringDataResponseDTO[]>> {
    try {
        // 使用工具函数解析 dataTypes 参数
        const dataTypes = this.parseDataTypes(dataTypesParam);

        if (!dataTypes || dataTypes.length === 0) {
            return {
                code: 400,
                message: 'dataTypes 参数不能为空',
                timestamp: Date.now()
            };
        }

        const result = await this.monitoringDataService.findByDataTypes(dataTypes, stationCode, stationTypeCode, limit);
        return {
            code: 200,
            message: '查询成功',
            data: result,
            timestamp: Date.now()
        };
    } catch (error) {
        return {
            code: 500,
            message: error.message || '查询失败',
            timestamp: Date.now()
        };
    }
}

    /**
     * 根据测站编码查询监测数据
     */
    @ApiOperation({ summary: '根据测站编码查询监测数据' })
    @ApiParam({ name: 'stationCode', description: '测站编码' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/by-station/:stationCode')
    async findByStationCode(
        @Param('stationCode') stationCode: string,
        @Query('limit') limit?: number
    ): Promise<CommonResponseDTO<MonitoringDataResponseDTO[]>> {
        try {
            const result = await this.monitoringDataService.findByStationCode(stationCode, limit);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据测站类型编码查询监测数据
     */
    @ApiOperation({ summary: '根据测站类型编码查询监测数据' })
    @ApiParam({ name: 'stationTypeCode', description: '测站类型编码' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/by-station-type/:stationTypeCode')
    async findByStationTypeCode(
        @Param('stationTypeCode') stationTypeCode: string,
        @Query('limit') limit?: number
    ): Promise<CommonResponseDTO<MonitoringDataResponseDTO[]>> {
        try {
            const result = await this.monitoringDataService.findByStationTypeCode(stationTypeCode, limit);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }
    /**
     * 根据时间范围查询监测数据 - 支持 dataTypes 多选
     */
    @ApiOperation({ summary: '根据时间范围查询监测数据，支持多选数据类型' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/by-date-range')
    async findByDateRange(
        @Query('startDate') startDate: string,
        @Query('endDate') endDate: string,
        @Query('stationCode') stationCode?: string,
        @Query('dataTypes') dataTypesParam?: string,
        @Query('stationTypeCode') stationTypeCode?: string
    ): Promise<CommonResponseDTO<MonitoringDataResponseDTO[]>> {
        try {
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            // 处理 dataTypes 参数
            let dataTypes: string[] | undefined;
            if (dataTypesParam) {
                try {
                    dataTypes = JSON.parse(dataTypesParam);
                } catch {
                    dataTypes = dataTypesParam.split(',').map(item => item.trim());
                }
                dataTypes = dataTypes.filter(item => item && item.length > 0);
            }

            const result = await this.monitoringDataService.findByDateRange(start, end, stationCode, dataTypes, stationTypeCode);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 获取最新监测数据 - 支持多个数据类型
     */
    @ApiOperation({ summary: '获取最新监测数据，支持多选数据类型' })
    @ApiResponse({ status: 200, description: '查询成功', type: CommonResponseDTO })
    @Get('/latest')
    async findLatestData(
        @Query('stationCode') stationCode?: string,
        @Query('stationTypeCode') stationTypeCode?: string,
        @Query('dataTypes') dataTypesParam?: string,
        @Query('limit') limit?: number
    ): Promise<CommonResponseDTO<MonitoringDataResponseDTO[]>> {
        try {
            // 处理 dataTypes 参数
            let dataTypes: string[] | undefined;
            if (dataTypesParam) {
                try {
                    dataTypes = JSON.parse(dataTypesParam);
                } catch {
                    dataTypes = dataTypesParam.split(',').map(item => item.trim());
                }
                dataTypes = dataTypes.filter(item => item && item.length > 0);
            }

            const result = await this.monitoringDataService.findLatestData(stationCode, stationTypeCode, dataTypes, limit);
            return {
                code: 200,
                message: '查询成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '查询失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 更新监测数据
     */
    @ApiOperation({ summary: '更新监测数据' })
    @ApiParam({ name: 'id', description: '监测数据ID' })
    @ApiResponse({ status: 200, description: '更新成功', type: CommonResponseDTO })
    @Put('/:id')
    async update(
        @Param('id') id: string,
        @Body() updateDto: UpdateMonitoringDataDTO
    ): Promise<CommonResponseDTO<MonitoringDataResponseDTO>> {
        try {
            const result = await this.monitoringDataService.update(id, updateDto);
            return {
                code: 200,
                message: '更新成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '更新失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 删除监测数据
     */
    @ApiOperation({ summary: '删除监测数据' })
    @ApiParam({ name: 'id', description: '监测数据ID' })
    @ApiResponse({ status: 200, description: '删除成功', type: CommonResponseDTO })
    @Del('/:id')
    async delete(@Param('id') id: string): Promise<CommonResponseDTO<boolean>> {
        try {
            const result = await this.monitoringDataService.delete(id);
            return {
                code: 200,
                message: result ? '删除成功' : '删除失败，记录不存在',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '删除失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 批量删除监测数据
     */
    @ApiOperation({ summary: '批量删除监测数据' })
    @ApiResponse({ status: 200, description: '删除成功', type: CommonResponseDTO })
    @Del('/batch')
    async batchDelete(@Body() batchDeleteDto: BatchDeleteDTO): Promise<CommonResponseDTO<number>> {
        try {
            const result = await this.monitoringDataService.batchDelete(batchDeleteDto.ids);
            return {
                code: 200,
                message: `成功删除 ${result} 条记录`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '批量删除失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 批量导入监测数据
     */
    @ApiOperation({ summary: '批量导入监测数据' })
    @ApiResponse({ status: 200, description: '导入成功', type: CommonResponseDTO })
    @Post('/batch-import')
    async batchImport(@Body() batchImportDto: BatchImportMonitoringDataDTO): Promise<CommonResponseDTO<MonitoringDataResponseDTO[]>> {
        try {
            const result = await this.monitoringDataService.batchImport(batchImportDto.monitoringDataList);
            return {
                code: 200,
                message: `成功导入 ${result.length} 条记录`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 400,
                message: error.message || '批量导入失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 获取数据统计信息
     */
    @ApiOperation({ summary: '获取数据统计信息' })
    @ApiParam({ name: 'stationCode', description: '测站编码' })
    @ApiResponse({ status: 200, description: '统计成功', type: CommonResponseDTO })
    @Get('/statistics/:stationCode')
    async getDataStatistics(
        @Param('stationCode') stationCode: string,
        @Query('stationTypeCode') stationTypeCode?: string
    ): Promise<CommonResponseDTO<DataStatisticsDTO>> {
        try {
            const result = await this.monitoringDataService.getDataStatistics(stationCode, stationTypeCode);
            return {
                code: 200,
                message: '统计成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '统计失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 根据测站编码和数据类型获取数据统计
     */
    @ApiOperation({ summary: '根据测站编码和数据类型获取数据统计' })
    @ApiParam({ name: 'stationCode', description: '测站编码' })
    @ApiResponse({ status: 200, description: '统计成功', type: CommonResponseDTO })
    @Get('/statistics-by-type/:stationCode')
    async getDataStatisticsByType(
        @Param('stationCode') stationCode: string,
        @Query('dataType') dataType?: string,
        @Query('stationTypeCode') stationTypeCode?: string
    ): Promise<CommonResponseDTO<DataStatisticsDTO>> {
        try {
            const result = await this.monitoringDataService.getDataStatisticsByType(stationCode, dataType, stationTypeCode);
            return {
                code: 200,
                message: '统计成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '统计失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 统计所有测站数据数量
     */
    @ApiOperation({ summary: '统计所有测站数据数量' })
    @ApiResponse({ status: 200, description: '统计成功', type: CommonResponseDTO })
    @Get('/count-by-station')
    async countByStation(): Promise<CommonResponseDTO<{ stationCode: string; stationTypeCode?: string; count: number }[]>> {
        try {
            const result = await this.monitoringDataService.countByStation();
            return {
                code: 200,
                message: '统计成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '统计失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 按测站类型统计数据
     */
    @ApiOperation({ summary: '按测站类型统计数据' })
    @ApiResponse({ status: 200, description: '统计成功', type: CommonResponseDTO })
    @Get('/count-by-station-type')
    async countByStationType(): Promise<CommonResponseDTO<{ stationTypeCode: string; stationTypeName?: string; count: number }[]>> {
        try {
            const result = await this.monitoringDataService.countByStationType();
            return {
                code: 200,
                message: '统计成功',
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '统计失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 清理过期数据
     */
    @ApiOperation({ summary: '清理过期数据' })
    @ApiResponse({ status: 200, description: '清理成功', type: CommonResponseDTO })
    @Del('/cleanup')
    async deleteExpiredData(@Query('beforeDate') beforeDate: string): Promise<CommonResponseDTO<number>> {
        try {
            const date = new Date(beforeDate);
            const result = await this.monitoringDataService.deleteExpiredData(date);
            return {
                code: 200,
                message: `成功清理 ${result} 条过期数据`,
                data: result,
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '清理失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 清理缓存
     */
    @ApiOperation({ summary: '清理缓存' })
    @ApiResponse({ status: 200, description: '清理成功', type: CommonResponseDTO })
    @Post('/clear-cache')
    async clearCaches(): Promise<CommonResponseDTO<string>> {
        try {
            await this.monitoringDataService.clearCaches();
            return {
                code: 200,
                message: '缓存清理成功',
                data: '所有缓存已清理',
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '缓存清理失败',
                timestamp: Date.now()
            };
        }
    }

    /**
     * 刷新缓存
     */
    @ApiOperation({ summary: '刷新缓存' })
    @ApiResponse({ status: 200, description: '刷新成功', type: CommonResponseDTO })
    @Post('/refresh-cache')
    async refreshCaches(): Promise<CommonResponseDTO<string>> {
        try {
            await this.monitoringDataService.refreshCaches();
            return {
                code: 200,
                message: '缓存刷新成功',
                data: '所有缓存已刷新',
                timestamp: Date.now()
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '缓存刷新失败',
                timestamp: Date.now()
            };
        }
    }
}